package com.atguigu.spzx.manner.util;

import com.atguigu.spzx.model.entity.SysMenu;
import com.atguigu.spzx.model.vo.common.SysMenuVo;

import java.util.ArrayList;
import java.util.List;

public class MenuHelper {

    public static List<SysMenu> buildTree(List<SysMenu> sysMenuList) {
        ArrayList<SysMenu> tree = new ArrayList<>();
        for (SysMenu sysMenu : sysMenuList) {
            if (sysMenu.getParentId() == 0) {
                tree.add(findChildren(sysMenu, sysMenuList));
            }

        }
        return tree;


    }

    private static SysMenu findChildren(SysMenu parent, List<SysMenu> sysMenuList) {
        parent.setChildren(new ArrayList<>());
        for (SysMenu son : sysMenuList) {
            if (son.getParentId().longValue() == parent.getId().longValue()) {
                List<SysMenu> children = parent.getChildren();
                children.add(findChildren(son, sysMenuList));

            }
        }
        return parent;
    }

    public static List<SysMenuVo> buildMenuVoList(List<SysMenu> sysMenuList) {
        ArrayList<SysMenuVo> sysMenuVos = new ArrayList<>();
        for (SysMenu sysMenu : sysMenuList) {
            SysMenuVo sysMenuVo = new SysMenuVo();
            sysMenuVo.setTitle(sysMenu.getTitle());
            sysMenuVo.setName(sysMenu.getComponent());
            if (sysMenu.getChildren() != null && !sysMenu.getChildren().isEmpty()) {
                sysMenuVo.setChildren(buildMenuVoList(sysMenu.getChildren()));
            }

            sysMenuVos.add(sysMenuVo);
        }
        return sysMenuVos;
    }
}
